//
//  LGRequestable.swift
//  swiftLingo
//
//  Created by lingo on 2017/10/8.
//  Copyright © 2017年 livefor. All rights reserved.
//

import Foundation
import Alamofire
import PKHUD
import Qiniu
//baseUrl
var baseUrl: String{return "http://192.168.199.219:8360"}

enum MethodType {
    case get
    case post
}
protocol LGRequestable {
    var urlString : String{get}
    var type: MethodType{get}
    var parameters: [String : Any]{get}
    func parseResult(_ result: Any)
}

extension LGRequestable {
    func requestData(resultCallBack:@escaping()->()) -> Void {
        let method = type == .get ? HTTPMethod.get : HTTPMethod.post
        let fullUrl = baseUrl.appending(urlString)
        HUD.show(.progress)
        Alamofire.request(fullUrl, method: method, parameters: parameters).responseJSON { (response: DataResponse<Any>) in
            guard response.result.isSuccess else {
                HUD.flash(.labeledProgress(title: "", subtitle: "网络请求错误"), delay: hudDelay)
                //错误原因
                resultCallBack()
                return
            }
            
            guard let json = response.result.value else {
                HUD.flash(.labeledProgress(title: "", subtitle: "数据错误"), delay: hudDelay)
                //报出错误原因
                resultCallBack()
                return
            }
            
            guard let jsonDict = json as? [String: Any] else {
                HUD.flash(.labeledProgress(title: "", subtitle: "解析失败"), delay: hudDelay)
                //报出错误原因
                resultCallBack()
                return
            }
            
            guard let resCode = jsonDict["code"] as? Int else {
                HUD.flash(.labeledProgress(title: "", subtitle: "网络请求错误"), delay: hudDelay)
                //报出错误原因
                resultCallBack()
                return
            }
            ///请求成功 数据正常
            if resCode == SUCCESS_CODE {//表示请求成功
                guard let resData = jsonDict["data"] else {
                    //报出错误原因
                    HUD.flash(.labeledProgress(title: "", subtitle: "解析失败"), delay: hudDelay)
                    return
                }
                self.parseResult(resData)
               
                HUD.hide()
                resultCallBack()
                return
            }
            ///其他错误判断
           // if resCode == DATA_ERROR {
                let msg = jsonDict["msg"] as? String
                HUD.flash(.labeledProgress(title:"" , subtitle: msg), delay: hudDelay)
                resultCallBack()
                return
           // }
        }
    }
}

